﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Data;
using System.Dynamic;

namespace RazorSourceGenerator
{
    public class GeneratorUtils
    {
        private static XmlSerializer _xmlSerialzer = new XmlSerializer(typeof(GeneratorConfig));

        public static string GetActualFileName(string workDir, string fileName)
        {
            if (!string.IsNullOrEmpty(fileName) && !Path.IsPathRooted(fileName))
            {
                return Path.Combine(workDir, fileName);
            }
            return fileName;
        }

        public static string ConvName(string tableName)
        {
            var str = string.Join("", tableName.ToLower().Split('_', ' ').Select(s => char.ToUpper(s[0]).ToString() + s.Substring(1)).ToArray());
            var result = char.ToUpper(str[0]).ToString() + str.Substring(1);
            return result;
        }

        public static GeneratorConfig LoadConfig(string fileName)
        {
            GeneratorConfig config = null;
            using (var fs = File.OpenRead(fileName))
            {
                config = _xmlSerialzer.Deserialize(fs) as GeneratorConfig;
                return config;
            }
        }

        public static void SaveConfig(GeneratorConfig config, string fileName)
        {
            using (var fs = File.Create(fileName))
            {
                _xmlSerialzer.Serialize(fs, config);
            }
        }

        public static IEnumerable<dynamic> ConvertTableToDynamicCollection(DataTable table)
        { 
            var result = table.AsEnumerable().Select(row => {
                dynamic columnSchema = new ExpandoObject();
                foreach (DataColumn col in table.Columns)
                {
                    var dict = (IDictionary<string, object>)columnSchema;
                    dict[col.ColumnName] = row[col.ColumnName].ToString();
                }
                return columnSchema;
            });
            return result.ToList();
        }
    }
}
